import React, { useEffect, useState } from "react";
import { Checkbox, Form, Input } from "antd";
import { QuestionInputPropsType } from "./interface";

const PropComponent: React.FC<QuestionInputPropsType> = (
  props: QuestionInputPropsType
) => {
  const {
    title,
    placeholder,
    prompt,
    isRequired,
    isUnique,
    onChange,
    disabled,
  } = props;
  const [form] = Form.useForm();
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    form.setFieldsValue({ title, placeholder, prompt, isRequired, isUnique });
  }, [title, placeholder, prompt, isRequired, isUnique]);

  function handleValueChange() {
    if (onChange) onChange(form.getFieldsValue());
  }

  function handleBlur() {
    const currentValue = form.getFieldValue("title");

    if (currentValue !== "") return;
    form.setFieldValue("title", inputValue);
    if (onChange) onChange(form.getFieldsValue());
    form.resetFields();
  }

  return (
    <Form
      layout="vertical"
      initialValues={{ title, placeholder, prompt, isRequired, isUnique }}
      form={form}
      onValuesChange={handleValueChange}
      disabled={disabled}
    >
      <Form.Item
        label="标题"
        name="title"
        rules={[{ required: true, message: "请输入标题" }]}
      >
        <Input
          onFocus={(e) => setInputValue(e.target.value)}
          onBlur={handleBlur}
          allowClear
        />
      </Form.Item>
      <Form.Item label="占位符" name="placeholder">
        <Input allowClear />
      </Form.Item>
      <Form.Item label="提示答案" name="prompt">
        <Input allowClear />
      </Form.Item>
      <Form.Item name="isRequired" valuePropName="checked">
        <Checkbox>是否必填</Checkbox>
      </Form.Item>
      <Form.Item name="isUnique" valuePropName="checked">
        <Checkbox style={{ position: "relative" }}>
          唯一答案（开启后此题目无法提交重复值）
          <div
            style={{
              position: "absolute",
              top: "100%",
              width: "100%",
              color: "#999",
            }}
          >
            请在图层面板给此题目设置一个标题
          </div>
        </Checkbox>
      </Form.Item>
    </Form>
  );
};

export default PropComponent;
